<script lang="ts" setup>
import {Delete, Search} from "@element-plus/icons-vue";
import {onBeforeMount, ref} from "vue";
import type {Ref} from "vue";
import type {PageRetainRequest, RetainResponse} from "@/api/retain";
import {deleteRetain, pageRetain} from "@/api/retain";
import {ElMessage} from "element-plus";

const retainData: Ref<RetainResponse[]> = ref([])
const pageRetainRequest: Ref<PageRetainRequest> = ref({
  pageIndex: 1,
  pageSize: 10
})
const total: Ref<number> = ref(0)

onBeforeMount(() => {
  pageRetainData();
})

function pageRetainData(): void {
  pageRetain(pageRetainRequest.value).then(res => {
    total.value = Number(res.data.total);
    retainData.value = res.data.body
  })
}

function currentChange(value: number): void {
  pageRetainRequest.value.pageIndex = value
  pageRetainData()
}

function removeRetainMessage(topic: string): void {
  deleteRetain(topic).then(res => {
    if (res.data.body) {
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
    pageRetainData()
  })
}

</script>

<template>
  <el-row>
    <el-input v-model="pageRetainRequest.topic" placeholder="主题" clearable/>
    <el-button type="primary" :icon="Search" @click="pageRetainData">搜索</el-button>
  </el-row>
  <el-table max-height="60vh" :data="retainData" empty-text="暂无数据">
    <el-table-column min-width="100px" prop="topic" label="主题"/>
    <el-table-column min-width="100px" prop="qos" label="qos"/>
    <el-table-column min-width="100px" prop="clientId" label="客户端 id"/>
    <el-table-column min-width="100px" label="操作">
      <template #default="scope">
        <el-popover placement="right" :width="400" trigger="click">
          <template #reference>
            <el-button type="primary" plain size="small">查看 payload</el-button>
          </template>
          <el-input v-model="scope.row.message" autosize type="textarea" disabled/>
        </el-popover>
        <el-popconfirm title="确认要删除此保留消息吗？" confirm-button-text="确认" cancel-button-text="取消"
                       confirm-button-type="danger" @confirm="removeRetainMessage(scope.row.topic)">
          <template #reference>
            <el-button type="danger" size="small" plain :icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination layout="prev, pager, next" :page-size="pageRetainRequest.pageSize" :total="total"
                 :current-page="pageRetainRequest.pageIndex" @current-change="currentChange" hide-on-single-page/>
</template>

<style scoped>
.el-input {
  width: 230px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-table {
  width: 100%;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
}
</style>